﻿var htmlImageList = '';
var htmlImageSingle = '';
var timeUpload = 0;
var isMulti = false;
var imageSize = 260;
var itemTinyMce = null;

function sleepFor(sleepDuration) {
    var now = new Date().getTime();
    while (new Date().getTime() < now + sleepDuration) {
        /* do nothing */
    }
}

function getExtension(filename) {
    var parts = filename.split('.');
    return parts[parts.length - 1];
}

function isImage(filename) {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) {
        case 'jpg':
        case 'gif':
        case 'png':
            return true;
    }
    return false;
}

function showButtonUpload() {
    $('.upload').show();
    $('.note').show();
}

function hideButtonUpload() {
    $('.upload').hide();
    $('.note').hide();
}

function openFileDialog() {
    if (isMulti)
        $("#fileUpload").click();
    else
        $("#fileUploadSingle").click();
}

function disabledButton(id, disabled) {
    document.getElementById(id).disabled = disabled;
}

function removeImageEvent() {
    $('#filesSelect span>b').click(function () {
        $(this).parent().parent().remove();
        if ($('#filesSelect').html() == '') {
            showButtonUpload();
        }
    });
}

function imageIsLoaded(e) {
    var imageData = e.target.result.split(',', 2)[1];
    uploadImage(imageData);
}

function getHtmlImageList(imageUrl, imageUrlScale) {
    htmlImageList += '<div class="img-item">';
    htmlImageList += '<span><b>x</b></span>';
    htmlImageList += '<img src="' + imageUrlScale + '" width="180px" height="150px" />';
    htmlImageList += '<input type="hidden" class="" value="' + imageUrl + '" />';
    htmlImageList += '</div>';
    return htmlImageList;
}

function getHtmlImage(imageUrl, imageUrlScale) {
    htmlImageSingle += '<img src="' + imageUrlScale + '" />';
    $('.thumbnailAvatar').val(imageUrl);
    //For TinyMCE
    if (itemTinyMce != null && itemTinyMce != undefined)
        itemTinyMce.insertContent('<img src="' + imageUrlScale + '" />');
    return htmlImageSingle;
}

function uploadImage(imageSource) {
    $.ajax({
        type: "POST",
        url: "/ajax.html",
        data: {
            "function": "UploadImageAjax",
            "imageData": imageSource,
            "imageSize": imageSize
        },
        dataType: "json",
        success: function (data) {
            if (!data.isError) {
                if (isMulti && data.imageUrl != '' && data.imageUrlScale != '') {
                    getHtmlImageList(data.imageUrl, data.imageUrlScale);
                } else if (!isMulti) {
                    getHtmlImage(data.imageUrl, data.imageUrlScale);
                }
            }
        }
    });
}
    
function previewImage(htmlImage) {  
    $('#filesSelect').append(htmlImage);
    removeImageEvent(); //Add event remove for image current
}

function parseImageByte(file) {
    if (isImage(file.name)) {
        var reader = new FileReader();
        reader.onload = imageIsLoaded;
        reader.readAsDataURL(file);
    }
}

function readImages(arrayFile) {
    if (!arrayFile) return;
    
    for (var i = 0; i < arrayFile.length; i++) {
        parseImageByte(arrayFile[i]);
    }
    timeUpload = i * 3000;
}

function progressBar(pbClass) {
    if (isMulti)
        disabledButton('btnAttachImage', true);

    $(pbClass).show();
    $(pbClass + '-bar').animate({
        width: '100%'
    }, timeUpload, function () {
        if (isMulti) {
            disabledButton('btnAttachImage', false);
            previewImage(htmlImageList);
            htmlImageList = '';
            isMulti = false;
        } else {
            $(pbClass).hide();
            $('.upload-result').html(htmlImageSingle);        
            htmlImageSingle = '';
        }
        timeUpload = 0;
    });
}

function clearProgressBar(pbClass) {
    //$('.progress').hide();
    //$('.progress-bar').css('width', '0');
    $(pbClass).hide();
    $(pbClass + '-bar').css('width', '0');
}

function getImagePaths() {
    var imagePaths = '';
    $('.img-item').each(function () {
        imagePaths += $(this).find('input').val() + '|';
    });
    return imagePaths;
}

/*============ Custom =============*/
function addImagePreview() {
    var imageScales = '';
    $('.img-item').each(function () {
        imageScales += $(this).find('img').attr('src') + '|';
    });
    var arrayImageScale = imageScales.split('|');
    var i = 0;
    $('.cp-upload>a').each(function() {
        $(this).find('img').attr('src', arrayImageScale[i]);
        i++;
    });
}

function setEditor(editor) {
    itemTinyMce = editor;
}

/*============ Event ==============*/
$(function () {
    /*======= Start Multi Image Upload ==============*/
    $('#btnUpload').click(function () {
        isMulti = true;
        itemTinyMce = null;
        clearProgressBar('.progress');
        openFileDialog();
    });
    $('#btnAttachImage').click(function () {
        isMulti = true;
        itemTinyMce = null;
        clearProgressBar('.progress');
        openFileDialog();
    });
    $("#fileUpload").change(function () {
        imageSize = 180;
        hideButtonUpload();
        readImages(this.files);
        progressBar('.progress');
    });
    $('#btnSubmit').click(function() {
        $('.thumbnailAlbum').val(getImagePaths());
        closePopup('upload');
        if ($(this).attr('show') == 1) {
            addImagePreview();
        }
    });
    /*======= End Multi Image Upload ==============*/
    
    /*======= Start Single Image Upload ==============*/
    $('#btnUploadSingle').click(function () {
        itemTinyMce = null;
        htmlImageSingle = '';
        clearProgressBar('.af-progress');
        openFileDialog();
    });
    $('#fileUploadSingle').change(function () {
        imageSize = 200;
        readImages(this.files);
        progressBar('.af-progress');
    });
    /*======= End Single Image Upload ==============*/

    /*======= Start TinyMCE Image Upload ==============*/
    $('#fileUploadTinyMce').change(function () {
        imageSize = 800;
        readImages(this.files);
    });
    /*======= End TinyMCE Image Upload ==============*/
});

